package controller

import (
	"ginfast/api/weixin/dto"
	"ginfast/api/weixin/model"
	"ginfast/pkg/dao"
	"ginfast/pkg/gctx"

	"github.com/gin-gonic/gin"
)

// User 用户
type User struct {
}

// PageHandler 列表
func (o *User) PageHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	var data []model.User
	total, _ := p.DbModelWhere(&model.User{}).Find(&data)
	gctx.JSONWrite(gin.H{"total": total, "rows": data}, c)
}

// GetHandler 查询
func (o *User) GetHandler(c *gin.Context) {
	dao.QueryByID(&model.User{}, c)
}

// AddHandler 新增
func (o *User) AddHandler(c *gin.Context) {
	var p model.User
	if err := c.ShouldBind(&p.UserOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := dao.DbCreate(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// UpdateRemarkHandler 更新
func (o *User) UpdateRemarkHandler(c *gin.Context) {
	var p model.User
	if err := c.ShouldBind(&p.UserOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := dao.DbUpdateColById(&model.User{}, p.ID, "remark", p.Remark); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

func (o User) Routers(r *gin.RouterGroup) {
	r.GET("", o.AddHandler)
	r.GET("/page", o.PageHandler)
	r.POST("", o.AddHandler)
	r.PUT("/remark", o.UpdateRemarkHandler)
}
